package freakin.wify;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;

public class WifyActivity extends Activity {

	private static final String TAG = "WifyActivity";

	TextView tvStatus;
	TextView tvNearestNetworkLabel;
	TextView tvNearestNetworkCoords;
	Button btnStatus;
	Button btnFindNearestNetwork;
	Button btnShowMap;
	CheckBox cbOnlyOpen;

	WifiApp app;
	NetworkManager nm;

	/** Used to not run two network searches... **/
	boolean networkSearchInProgress;

	public static final int STATUS_CHANGE = 12356;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.wifymain);
		Log.d(TAG, "creating activity");

		networkSearchInProgress = false;

		app = (WifiApp) getApplication();
		nm = app.nm;
		loadPreferences();
		setUpControls(this);

		checkServiceState();
	}

	public void onResume() {
		super.onResume();
		Log.d(TAG, "resuming activity");
		checkServiceState();
	}

	private void loadPreferences() {
		Log.d(TAG, "loading preferences");
		SharedPreferences sharedPreferences = PreferenceManager
				.getDefaultSharedPreferences(getBaseContext());

		try {
			app.sendInterval = Long.parseLong(sharedPreferences.getString(
					getString(R.string.send_interval), "10")) * 1000 * 60;
		} catch (NumberFormatException nfe) {
			Log.e(TAG, "NumberFormatException in setting sendInterval");
		}

		try {
			app.scanInterval = Long.parseLong(sharedPreferences.getString(
					getString(R.string.updateInterval), "60")) * 1000; // *
																		// 1000,
																		// because
																		// it
																		// has
																		// to
																		// be
																		// converted
																		// to
																		// miliseconds
		} catch (NumberFormatException nfe) {
			Log.e(TAG, "NumberFormatException in setting scanInterval");
		}

		/*
		app.setUserPass(
				sharedPreferences.getString(getString(R.string.user_name), ""),
				sharedPreferences.getString(getString(R.string.user_pass), ""));
		*/

		Log.d(TAG, "Loading preferences completed");
	}

	private void setUpControls(final Context c) {
		tvStatus = (TextView) findViewById(R.id.tvServiceStatus);
		tvNearestNetworkLabel = (TextView) findViewById(R.id.tvNearestNetworkLabel);
		tvNearestNetworkCoords = (TextView) findViewById(R.id.tvNearestNetworkCoords);
		btnFindNearestNetwork = (Button) findViewById(R.id.btnFindNearestNetwork);
		btnStatus = (Button) findViewById(R.id.btnChangeServiceStatus);
		btnShowMap = (Button) findViewById(R.id.btnShowMap);
		cbOnlyOpen = (CheckBox) findViewById(R.id.cbOnlyOpen);

		btnStatus.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				new AsyncTask<Void, Void, Void>() {

					@Override
					protected void onPreExecute() {
						btnStatus.setEnabled(false);
					}

					@Override
					protected Void doInBackground(Void... params) {
						Intent i = new Intent(c, WifiService.class);
						i.addFlags(STATUS_CHANGE);
						startService(i);
						return null;
					}

					@Override
					protected void onPostExecute(Void params) {
						if (app.serviceActive) {
							btnStatus.setText(R.string.disable);
							tvStatus.setText(R.string.active);
						} else {
							btnStatus.setText(R.string.activate);
							tvStatus.setText(R.string.disabled);
						}
						btnStatus.setEnabled(true);
						// Disclaimer: It's not working when executing
						// checkServiceStatus() for reasons unknown to man.
					}

				}.execute((Void) null);

				/*
				 * new Runnable() { public void run() { try { for (int i = 0; i
				 * < 2; i++) { Thread.sleep(300); checkServiceState(); }
				 * 
				 * } catch (InterruptedException e) { e.printStackTrace(); } }
				 * }.run(); new Runnable() { public void run() { try {
				 * Thread.sleep(600);
				 * 
				 * } catch (InterruptedException e) { e.printStackTrace(); } }
				 * }.run();
				 */
			}

		});

		btnFindNearestNetwork.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				Log.d(TAG, "button - find nearest network");

				if (!networkSearchInProgress)
					new NetworkFinder().execute(new Boolean[] { cbOnlyOpen
							.isChecked() });
				else
					Log.d(TAG, "network search already in progress...");

			}
		});

		btnShowMap.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Log.d(TAG, "starting Google Maps");
				startActivity(new Intent(c, Map.class));
			}
		});

	}

	private void checkServiceState() {
		Log.d(TAG, "checking service state. Service is active? = "
				+ app.serviceActive);

		if (app.serviceActive) {
			btnStatus.setText(R.string.disable);
			tvStatus.setText(R.string.active);
		} else {
			btnStatus.setText(R.string.activate);
			tvStatus.setText(R.string.disabled);
		}
		btnStatus.invalidate();
		tvStatus.invalidate();

	}

	private class NetworkFinder extends AsyncTask<Boolean, Void, Network> {

		private static final String TAG = "WifiActivity.NetworkFinder";

		protected void onPreExecute() {
			networkSearchInProgress = true;
			btnFindNearestNetwork.setEnabled(false);
			Log.d(TAG, "preparing to execute worker thread...");
		}

		protected void onPostExecute(Network n) {
			if (n == null) {
				tvNearestNetworkCoords
						.setText(getString(R.string.findNearestNetworkFail));
				Log.d(TAG, "could not find nearest network...");
			} else {
				tvNearestNetworkCoords.setText("Found a network. \n"
						+ "BSSID: " + n.bssid + "\nSSID: " + n.ssid
						+ "\nLatitude: " + n.latitude + "\nLongitude: "
						+ n.longitude + "\nSecurity: " + n.security);
				Log.d(TAG, "Found nearest network.");
			}
			networkSearchInProgress = false;
			btnFindNearestNetwork.setEnabled(true);
		}

		// @Override
		protected Network doInBackground(Boolean... params) {
			Log.d(TAG, "computing nearest network...");
			Log.d(TAG, "only open? = " + params[0]);
			Network n = nm.getNearestNetwork(params[0]);
			Log.d(TAG, "returned the network. Is it null? = " + (n == null));
			return n;
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu, menu);
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.preferences:
			Log.d(TAG, "starting preferences");
			startActivity(new Intent(this, Preferences.class));
			return true;
		case R.id.deleteNetworks:
			Log.d(TAG, "deleting networks from the webservice...");
			new AsyncTask<Void, Void, Void>() {
				private static final String TAG = "WifyActivity->deleteNetworks";
				@Override
				protected void onPreExecute() {
					Log.d(TAG, "preparing to execute worker thread...");
				}

				@Override
				protected void onPostExecute(Void param) {
					Log.d(TAG, "execution completed");
				}
				
				@Override
				protected Void doInBackground(Void... params) {
					app.deleteNetworksFromWebservice();
					return null;
				}
			}.execute((Void)null);
			return true;
		}
		return false;
	}
}